/* eslint-disable no-useless-escape */
/* eslint-disable no-control-regex */
import fs from 'node:fs'
import path from 'node:path'

import * as XLSX from 'xlsx'

export default function useParseLang() {
  const filePath = process.argv[2]
  if (!filePath) {
    console.error('文件不存在')
    return
  }
  const inputPath = path.resolve(filePath)
  console.log('翻译文件', inputPath)
  fs.readFile(inputPath, 'binary', (err, data) => {
    if (err) {
      throw new Error(err)
    }
    const workBook = XLSX.read(data, { type: 'binary', cellDates: true })
    // const reg = /([^\x00-\xff])|([\?\.\(\)\$\:\u00A0\s,'-])|[0-9]/g // 去除key中的特殊字符数字,所有全角符号和部分半角符号
    const reg = /[\s\u00A0]+/g // 匹配一个或多个连续的空格字符或非断空格
    workBook.SheetNames.forEach(name => {
      const workSheet = workBook.Sheets[name]
      console.log('workSheet: ', workSheet)
      const rawList = XLSX.utils.sheet_to_json(workSheet, { header: 1 })
      const enObj = {}
      const zhObj = {}
      const zhPath = path.join(
        process.cwd(),
        `/src/locales/lang/zh-CN/${name}.json`
      )
      const enPath = path.join(
        process.cwd(),
        `/src/locales/lang/en-US/${name}.json`
      )
      // if (name === 'common') {
      //   zhPath = path.join(
      //     process.cwd(),
      //     `/packages/website/lang/zh-CN/website.json`
      //   )
      //   enPath = path.join(
      //     process.cwd(),
      //     `/packages/website/lang/en/website.json`
      //   )
      // } else {
      // }
      rawList.forEach(item => {
        const valueArr = item.slice(item.length - 2)
        const keyArr = item.slice(0, item.length - 2)
        const parseKeyArr = keyArr
          .map(key => {
            const tem = key.charAt(0).toLowerCase() + key.slice(1)
            return tem.replaceAll(reg, '')
          })
          .filter(Boolean)
        parseKeyArr.unshift(name)
        // const keyResult = name + '.' + parseKeyArr.join('.')
        const keyResult = parseKeyArr.join('.')
        zhObj[keyResult] = valueArr[0]
        enObj[keyResult] = valueArr[1]
      })

      fs.writeFileSync(zhPath, JSON.stringify(zhObj, null, 2))
      fs.writeFileSync(enPath, JSON.stringify(enObj, null, 2))
    })
  })
}

useParseLang()
